package com.zw.pdm.module.designtask.service;

import com.zw.pdm.entity.basic.Dept;
import com.zw.pdm.entity.com.DsnProCommon;
import com.zw.pdm.entity.com.DsnTaskCommon;
import com.zw.pdm.entity.designtask.DsnControlIntent;
import com.zw.pdm.entity.designtask.DsnProStruct;
import com.zw.pdm.entity.production.MakeResult;
import com.zw.pdm.entity.rep.Result;
import com.zw.pdm.module.designtask.mapper.DesignTaskMapper;
import com.zw.pdm.module.designtask.mapper.DsnProcessMapper;
import com.zw.pdm.module.designtask.model.DsnDrawChangeModel;
import com.zw.pdm.module.designtask.model.DsnProSingleModel;
import com.zw.pdm.module.designtask.model.DsnProcessModel;
import com.zw.pdm.module.designtask.repository.*;
import com.zw.pdm.module.report.model.Project;
import com.zw.pdm.module.system.repository.DeptRepository;
import com.zw.pdm.module.system.service.LogService;
import com.zw.pdm.util.FileUtils;
import com.zw.pdm.util.ShiroUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import static com.zw.pdm.util.BeanUtil.copy;

/**
 * @Description:
 * @Author: China.wsg
 * @Date: 2020/10/21 14:12
 */
@Service
@SuppressWarnings("all")
public class DsnProcessService {

    @Autowired
    private LogService logService;
    @Autowired
    private DsnProcessMapper dsnProcessMapper;
    @Value("${user.upload.path}")
    private String uploadPath;
    @Autowired
    private DesignTaskMapper designTaskMapper;
    @Autowired
    private DsnControlIntentRepository dsnControlIntentRepository;
    @Autowired
    private DeptRepository deptRepository;
    @Autowired
    private DsnProStructRepository dsnProStructRepository;
    @Autowired
    private DsnTaskCommonRepository dsnTaskCommonRepository;
    @Value("${saleUrl}")
    private String saleUrl;


    /**
     * 按条件查询设计进度看板
     *
     * @param dsnProcessModel
     * @return
     */
    public List<DsnProcessModel> findProcessListByQuery(DsnProcessModel dsnProcessModel) {
        return dsnProcessMapper.findProcessListByQuery(dsnProcessModel);
    }

    /**
     * 单项目看板项目任务状态
     *
     * @param proId
     * @return
     */
    public List<DsnProcessModel> findProProcessStatus(Integer proId) {
        return dsnProcessMapper.findProProcessStatus(proId);
    }

    /**
     * 项目说明列表
     *
     * @param dsnProExplain
     * @return
     */
    public List<DsnControlIntent> findExplainListByQuery(DsnControlIntent controlIntent) {
        return dsnProcessMapper.findExplainListByQuery(controlIntent);
    }

    /**
     * 产品部分状态列表
     *
     * @param dsnTaskCommon
     * @return
     */
    public List<DsnTaskCommon> findPartListByProId(Integer proId, Integer deptId) {
        String special = findDeptInfoByAccount(deptId);
        return dsnProcessMapper.findPartListByProId(proId, special);
    }

    /**
     * 根据科室ID取得所信息
     *
     * @param deptId
     * @return
     */
    public String findDeptInfoByAccount(Integer deptId) {
        Dept dept = dsnProcessMapper.findDeptInfoByAccount(deptId);
        String special = null;
        if (dept != null && (dept.getName().equals("挤压装备设计所") || dept.getName().equals("熔铸装备设计所")
                || dept.getName().equals("深加工装备设计所"))) {
            special = "机械";
        } else if (dept != null && dept.getName().equals("流体传动设计所")) {
            special = "流体";
        } else if (dept != null && dept.getName().equals("自动化与智能控制设计所")) {
            special = "自动化";
        }
        return special;
    }

    /**
     * 根据条件查询部分
     *
     * @param proId
     * @return
     */
    public List<DsnProStruct> findProStructByProId(Integer proId) {

        return dsnProcessMapper.findProStructByProId(proId);
    }

    /**
     * 外购、原料、外协列表（单项目看板）
     *
     * @param dsnProSingleModel
     * @return
     */
    public List<DsnProSingleModel> findProSingleListByQuery(DsnProSingleModel dsnProSingleModel) {
        if (dsnProSingleModel.getProPart().equals("机械")) {
            dsnProSingleModel.setProPart("");
            dsnProSingleModel.setSpecial("机械");
        } else if (dsnProSingleModel.getProPart().equals("流体")) {
            dsnProSingleModel.setProPart("");
            dsnProSingleModel.setSpecial("流体");
        } else if (dsnProSingleModel.getProPart().equals("自动化")) {
            dsnProSingleModel.setProPart("");
            dsnProSingleModel.setSpecial("自动化");
        }
        return dsnProcessMapper.findProSingleListByQuery(dsnProSingleModel);
    }

    /**
     * 制作件列表（单项目看板）
     *
     * @param dsnProSingleModel
     * @return
     */
    public List<DsnProSingleModel> findMakeSingleListByQuery(DsnProSingleModel dsnProSingleModel) {
        if (dsnProSingleModel.getProPart().equals("机械")) {
            dsnProSingleModel.setProPart("");
            dsnProSingleModel.setSpecial("机械");
        } else if (dsnProSingleModel.getProPart().equals("流体")) {
            dsnProSingleModel.setProPart("");
            dsnProSingleModel.setSpecial("流体");
        } else if (dsnProSingleModel.getProPart().equals("自动化")) {
            dsnProSingleModel.setProPart("");
            dsnProSingleModel.setSpecial("自动化");
        }
        return dsnProcessMapper.findMakeSingleListByQuery(dsnProSingleModel);
    }

    /**
     * 图纸变更单（单项目看板）
     *
     * @param dsnProSingleModel
     * @return drawChangeList
     */
    public List<DsnProSingleModel> findDrawChangeSingleListByQuery(DsnProSingleModel dsnProSingleModel) {
        if (dsnProSingleModel.getProPart().equals("机械")) {
            dsnProSingleModel.setProPart("");
            dsnProSingleModel.setSpecial("机械");
        } else if (dsnProSingleModel.getProPart().equals("流体")) {
            dsnProSingleModel.setProPart("");
            dsnProSingleModel.setSpecial("流体");
        } else if (dsnProSingleModel.getProPart().equals("自动化")) {
            dsnProSingleModel.setProPart("");
            dsnProSingleModel.setSpecial("自动化");
        }
        return dsnProcessMapper.findDrawChangeSingleListByQuery(dsnProSingleModel);
    }

    /**
     * 技术说明（单项目看板）
     *
     * @param dsnProSingleModel
     * @return tecNoteList
     */
    public List<DsnProSingleModel> findTecNoteListSingleListByQuery(DsnProSingleModel dsnProSingleModel) {
        if (dsnProSingleModel.getProPart().equals("机械")) {
            dsnProSingleModel.setProPart("");
            dsnProSingleModel.setSpecial("机械");
        } else if (dsnProSingleModel.getProPart().equals("流体")) {
            dsnProSingleModel.setProPart("");
            dsnProSingleModel.setSpecial("流体");
        } else if (dsnProSingleModel.getProPart().equals("自动化")) {
            dsnProSingleModel.setProPart("");
            dsnProSingleModel.setSpecial("自动化");
        }
        return dsnProcessMapper.findTecNoteListSingleListByQuery(dsnProSingleModel);
    }

    /**
     * 任务状态编辑
     *
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean editTaskStatusByQuery(DsnTaskCommon dsnTaskCommon) {

        String taskType = "";
        if (dsnTaskCommon.getComTaskNameId() == 5) {
            taskType = "设计";
        } else if (dsnTaskCommon.getComTaskNameId() == 6) {
            taskType = "控制意图";
        } else if (dsnTaskCommon.getComTaskNameId() == 7) {
            taskType = "成本";
        } else if (dsnTaskCommon.getComTaskNameId() == 8) {
            taskType = "调试";
        }

        dsnTaskCommon.setUpdateUser(ShiroUtils.getUser().getName());
        dsnTaskCommon.setUpdateTime(new Date());
        int rows = 0;
        if (dsnTaskCommon.getComTaskNameId() == 6) {
            // 修改控制意图状态
            rows = dsnProcessMapper.editConTaskStatusByQuery(dsnTaskCommon);
            Project project = designTaskMapper.findProjectById(dsnTaskCommon.getProId());
            logService.saveLog("修改设计任务状态", "项目编号：" + project.getCode() + "<br>任务类型：" + taskType);
        } else {
            // 修改设计、成本、调试
            rows = dsnProcessMapper.editTaskStatusByQuery(dsnTaskCommon);
            Dept dept = deptRepository.getOne(dsnTaskCommon.getDeptId());
            Project project = designTaskMapper.findProjectById(dsnTaskCommon.getProId());
            logService.saveLog("修改设计任务状态", "项目编号：" + project.getCode() + "<br>部门：" + dept.getName()
                    + "<br>任务类型：" + taskType);

            // 更新销售系统项目状态表中状态 注：跨系统 通过视图修改
            if (dsnTaskCommon.getComTaskNameId() == 5) {
                // 更新设计状态 design_status
                Integer designStatus = getProStatus(dsnTaskCommon);
                String a = saleUrl;
                boolean boolFlg = updateProStatus(saleUrl + "/projectScheduling/updateProDesignStatus", project.getCode(), designStatus, 5);
                if (!boolFlg) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return false;
                }
            } else if (dsnTaskCommon.getComTaskNameId() == 8) {
                // 更新调试状态 debugging_status
                Integer debuggingStatus = getProStatus(dsnTaskCommon);
                boolean boolFlg = updateProStatus(saleUrl + "/projectScheduling/updateProDebugStatus", project.getCode(), debuggingStatus, 8);
                if (!boolFlg) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 跨域修改 项目状态
     *
     * @param saleUrl   接口地址
     * @param proCode   项目编号
     * @param proStatus 项目状态
     * @return
     */
    private boolean updateProStatus(String saleUrl, String proCode, Integer proStatus, Integer comTaskNameId) {
        RestTemplate restTemplate = new RestTemplate();
        MultiValueMap<String, String> bodyMap = new LinkedMultiValueMap<>();
        bodyMap.add("proCode", proCode);
        bodyMap.add("proStatus", proStatus.toString());
        String completeTime = "";
        if (proStatus == 3) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            // 取得最晚结束时间
            Date lastDate = dsnProcessMapper.findProDsnDateByProIdAndTaskNameId(proCode, comTaskNameId);
            if (lastDate == null) {
                completeTime = null;
            } else {
                completeTime = simpleDateFormat.format(lastDate);
            }
        } else {
            completeTime = null;
        }
        bodyMap.add("completeTime", completeTime);
        return restTemplate.postForObject(saleUrl, bodyMap, Boolean.class);
    }

    /**
     * 部分任务状态编辑
     *
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public int editPartStatusByQuery(DsnTaskCommon dsnTaskCommon) {

        DsnProStruct dsnProStruct = dsnProStructRepository.getOne(dsnTaskCommon.getId());
        dsnTaskCommon.setUpdateUser(ShiroUtils.getUser().getName());
        dsnTaskCommon.setUpdateTime(new Date());
        int rows = 0;
        // 修改项目部分状态
        dsnTaskCommon.setDeptId(ShiroUtils.getUser().getDeptId());
        rows = dsnProcessMapper.editProPartCompStatusById(dsnTaskCommon);
        logService.saveLog("修改设计部分状态", "项目编号：" + dsnProStruct.getProCode() + "<br>部分名称：" + dsnProStruct.getProPart()
                + "<br>状态：【" + dsnProStruct.getCompStatus() + "】->" + "【" + dsnTaskCommon.getCompStatus() + "】");
        return rows;
    }

    /**
     * 任务状态编辑
     *
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public int performanceNoteEdit(DsnProCommon dsnProCommon) {

        logService.saveLog("绩效备注编辑", "项目ID：" + dsnProCommon.getProId());
        return dsnProcessMapper.performanceNoteEdit(dsnProCommon);
    }

    /**
     * 绩效备注查询
     *
     * @param proId
     * @return
     */
    public List<DsnProCommon> findProPerformanceNote(Integer proId) {

        return dsnProcessMapper.findProPerformanceNote(proId);
    }

    /**
     * 外购件输出表
     *
     * @param result
     * @return
     */
    public List<Result> findRepResultByQuery(Result result) {
        return dsnProcessMapper.findRepResultByQuery(result);
    }

    /**
     * 制作件输出表
     *
     * @param result
     * @return
     */
    public List<MakeResult> findMakeResultByQuery(MakeResult result) {
        return dsnProcessMapper.findMakeResultByQuery(result);
    }

    /**
     * 图纸变更输出表
     *
     * @param result
     * @return
     */
    public List<DsnDrawChangeModel> findDrawChangeDetailByQuery(DsnDrawChangeModel result) {
        return dsnProcessMapper.findDrawChangeDetailByQuery(result);
    }

    /**
     * 上传附件(项目说明)
     *
     * @param file 上传附件
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void uploadFileExp(MultipartFile file, Integer proId, String fileContent, Integer branchId) {
        // 取得项目信息
        Project project = designTaskMapper.findProjectById(proId);
        String path = uploadPath + project.getCode() + "/" + "proExplain/";
        String fileName = FileUtils.upload(file, path);
        String url = "/files/" + project.getCode() + "/" + "proExplain/" + fileName;

        DsnControlIntent dsnControlIntent = new DsnControlIntent();
        dsnControlIntent.setProId(project.getId());
        dsnControlIntent.setProCode(project.getCode());
        dsnControlIntent.setProName(project.getName());
        dsnControlIntent.setBranchId(branchId);
        dsnControlIntent.setFileName(fileName);
        dsnControlIntent.setFileContent(fileContent);
        dsnControlIntent.setUrl(url);
        dsnControlIntent.setCreateCode(ShiroUtils.getUser().getAccount());
        dsnControlIntent.setCreateName(ShiroUtils.getUser().getName());
        dsnControlIntent.setFileType(2);
        dsnControlIntentRepository.save(dsnControlIntent);
        logService.saveLog("项目说明上传", project.getCode() + "<br>" + fileName);
    }

    /**
     * 删除项目说明
     *
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public int delExplainById(Integer id) {

        // 控制意图
        DsnControlIntent dsnProExplain = dsnControlIntentRepository.getOne(id);
        String msg = "";
        if (dsnProExplain.getFileType() == 1) {
            msg = "删除控制意图文件";
        } else if (dsnProExplain.getFileType() == 2) {
            msg = "删除项目说明文件";
        } else if (dsnProExplain.getFileType() == 3) {
            msg = "删除调试任务文件";
        }
        logService.saveLog(msg, "项目编号：" + dsnProExplain.getProCode() + "<br>文件名称：" + dsnProExplain.getFileName());
        return dsnProcessMapper.delExplainById(id);
    }

    /**
     * 修改控制意图
     *
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public int updExplainById(DsnControlIntent controlIntent) {

        // 控制意图
        DsnControlIntent proExplain = dsnControlIntentRepository.getOne(controlIntent.getId());
        String msg = "";
        if (proExplain.getFileType() == 1) {
            msg = "修改控制意图文件";
        } else if (proExplain.getFileType() == 2) {
            msg = "修改项目说明文件";
        } else if (proExplain.getFileType() == 3) {
            msg = "修改调试任务文件";
        }
        logService.saveLog(msg, "项目编号：" + proExplain.getProCode() + "<br>文件名称：" + proExplain.getFileName());
        return dsnProcessMapper.updExplainById(controlIntent);
    }

    /**
     * 取得节点状态信息
     *
     * @param dsnTaskCommon
     * @return
     */
    public DsnTaskCommon findNodeStatusByQuery(DsnTaskCommon dsnTaskCommon) {
        return dsnProcessMapper.findNodeStatusByQuery(dsnTaskCommon);
    }

    /**
     * 取得项目字段状态
     *
     * @param dsnTaskCommon
     * @return
     */
    private Integer getProStatus(DsnTaskCommon dsnTaskCommon) {
        // 更新项目状态 任务执行状态（1=未开始 2=执行中 3=已完成 4=不需要）
        Float avgStatus = dsnProcessMapper.findProDsnStatusByProIdAndTaskNameId(dsnTaskCommon);
        Integer proStatus = 0;// 0：不需要，1=未开始，2=执行中，3=已完成
        if (avgStatus == 1) {
            proStatus = 1;
        } else if (avgStatus == 4) {
            proStatus = 0;
        } else if (avgStatus >= 3) {
            proStatus = 3;
        } else {
            proStatus = 2;
        }
        return proStatus;
    }

    /**
     * 取得控制意图节点状态信息
     *
     * @param dsnTaskCommon
     * @return
     */
    public DsnTaskCommon findNodeConStatusByQuery(DsnTaskCommon dsnTaskCommon) {
        return dsnProcessMapper.findNodeConStatusByQuery(dsnTaskCommon);
    }

    /**
     * 更新项目设计状态
     *
     * @param proId
     * @return
     */
    public int udpProDsnStatus(Integer proId, Integer specialId) {
        float dsnTaskStatus = dsnProcessMapper.findProDsnStatusByProIdAndSpecialId(proId, specialId);
        Integer status = 1;
        if (dsnTaskStatus == 1) {
            // 未开始
            status = 1;
        } else if (dsnTaskStatus == 3) {
            // 已完成
            status = 3;
        } else {
            // 执行中
            status = 2;
        }
        // 更新科室设计任务状态
        return dsnProcessMapper.udpProDsnStatusByProIdAndSpecialId(proId, specialId, status);
    }
}
